package com.leyou.order.controller;

import com.leyou.common.exception.LyException;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.service.OrderService;
import com.leyou.order.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单接口
     * @param orderDTO          接收请求的参数
     * @param bindingResult     异常校验结果
     * @return                  返回订单ID
     */
    @PostMapping("/order")
    public ResponseEntity<Long> createOrder(@Valid @RequestBody OrderDTO orderDTO, BindingResult bindingResult){
        // 手动从user中取出值来进行判空等校验： 服务器端校验
        if(bindingResult.hasErrors()){
            // 如果有异常，收集异常信息
            String errors = bindingResult.getAllErrors()
                    .stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(errors, 400);
        }
        // 创建订单
        Long orderId = orderService.createOrder(orderDTO);
        // 返回
        return ResponseEntity.ok(orderId);
    }

    /**
     * 根据订单编号查询订单
     * @param orderId 订单编号
     * @return        OrderVO对象
     */
    @GetMapping("/order/{id}")
    public ResponseEntity<OrderVO> findOrderById(@PathVariable("id") Long orderId){
        OrderVO orderVO = orderService.findOrderById(orderId);
        return ResponseEntity.ok(orderVO);
    }

    /**
     * 获取微信支付的链接
     * @param orderId
     * @return
     */
    @GetMapping("/order/url/{id}")
    public ResponseEntity<String> findPayUrl (@PathVariable("id") Long orderId){
        String payUrl = orderService.findPayUrl(orderId);
        return ResponseEntity.ok(payUrl);
    }

    /**
     * 查询订单的状态
     * @param orderId   订单编号
     * @return          返回订单的状态
     */
    @GetMapping("/order/state/{id}")
    public ResponseEntity<Integer> findOrderState (@PathVariable("id") Long orderId){
        Integer state = orderService.findOrderState(orderId);
        return ResponseEntity.ok(state);
    }
}
